package com.yxy.utils;

import com.yxy.base.BusinessException;
import com.yxy.dao.TenantExtendMapper;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.model.TenantExtend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author yuxiaoyang
 * @date 2020-10-18
 * 租户相关帮助类
 */
@Service
public class TenantHelper {
  @Autowired
  private TokenCheckUtil tokenCheckUtil;

  @Resource
  private TenantExtendMapper tenantExtendMapper;

  //从前端传参中获取tenant id list相关信息,进行构造查询sql
  public Set<Long> getTenantIdListFromFront(Long tenantId) throws BusinessException {
    // 从token中获取登录用户信息
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();
    if (tenantId == null) {// 取出用户所属租户下所有的数据
      tenantIdList = adminUser.getTenantIdList();
      // 筛选出其中的租户组, 并将组内的租户平铺展开,放入tenantIdList
      Set<Long> tenantIdList2 = new HashSet<>();
      for (Long curTenantId : tenantIdList) {
        // 检查curTenantId是否为 租户组
        TenantExtend curTenant = tenantExtendMapper.selectByPrimaryKey(curTenantId);
        if ("group".equals(curTenant.getType())) {
          List<TenantExtend> tenantExtendList = this.getTenantListByGroup(curTenant.getId());
          for (TenantExtend tenantExtend9 : tenantExtendList) {
            tenantIdList2.add(tenantExtend9.getId());
          }
        } else {
          tenantIdList2.add(curTenantId);
        }
      }
      tenantIdList = tenantIdList2;
    } else { //前端传递了tenant id
      if (!adminUser.getTenantIdList().contains(tenantId)) { // 判断前端传递的tenantId是否属于该用户
        throw new BusinessException(510, "前端传递的tenantId不属于该用户");
      }
      // 检查tenantId是否为 租户组
      TenantExtend curTenant = tenantExtendMapper.selectByPrimaryKey(tenantId);
      if ("group".equals(curTenant.getType())) {
        List<TenantExtend> tenantExtendList = this.getTenantListByGroup(tenantId);
        tenantIdList = new HashSet<>();
        for (TenantExtend childTenant : tenantExtendList) {
          tenantIdList.add(childTenant.getId());
        }
      } else {
        tenantIdList.add(tenantId);
      }
    }
    return tenantIdList;
  }

  // 根据租户组id查询组内所有的租户列表
  public List<TenantExtend> getTenantListByGroup(Long groupId) {
    TenantExtend queryObj = new TenantExtend();
    queryObj.setType("common");
    queryObj.setGroupId(groupId);
    queryObj.setStatus(0L);
    List<TenantExtend> tenantExtendList = tenantExtendMapper.select(queryObj);
    return tenantExtendList;
  }
}
